<template>
	<div class="wrapper" :style="'top:'+statusBarHeight+'px'">
		<view class="header">
			<view class="back_div">
				<image class="back_img" @click="back_city()" src="../../static/back_img.png" style="margin-top: 4rpx;"
					mode=""></image>
			</view>
			<input class="input" @input="onInput" placeholder="中文/拼音/首字母" v-model="searchValue" />
		</view>
		<scroll-view class="calendar-list" scroll-y="true" :scroll-into-view="scrollIntoId">
			<view v-if="disdingwei" id="hot">
				<view class="dangqian" v-if="select != ''">
					<view class="left_title family f500 s24">
						当前：{{select ? select : selection}}
					</view>
					<view class="right_active_title family f500 s26 flex" @click="active">
						切换区县<view class="right_icon_box"
							:style="{'transform':flag ? 'rotateZ(90deg)' : 'rotateZ(0deg)'}"></view>
					</view>
				</view>
				<view class="dangqian" v-if="select == ''">
					<view class="left_title family f500 s24">
						当前：{{position}}
					</view>
					<view class="right_active_title family f500 s26 flex" @click="onSelect">
						切换区县<view class="right_icon_box"
							:style="{'transform':flag ? 'rotateZ(90deg)' : 'rotateZ(0deg)'}"></view>
					</view>
				</view>
				<view class="dq_list_box" :style="{'height':flag ? '100%' : '0'}">
					<view class="dq_list family f500 s26 txtali" v-for="(item,index) in selectList" :key="index"
						@click="back_city(item)">
						{{item.name}}
					</view>
				</view>
				<!-- 定位模块 -->
				<view class="dingwei">
					<view class="dingwei_Tips">
						当前定位
					</view>
					<view class="dingwei_city">
						<view class="dingwei_city_one" @click="onPosition">
							{{position}}
						</view>
						<view class="dingweis_div" @click="getWarpweft">
							<image class="dingweis" src="../../static/dingweis.png" mode=""></image>
							<text>{{po_tips}}</text>
						</view>
					</view>
				</view>

				<!-- 最近模块 -->
				<view class="dingwei" v-if="Visit.length>=0">
					<view class="dingwei_Tips">
						最近访问
					</view>
					<view class="dingwei_city dingwei_city_zuijin">
						<view class="dingwei_city_one toright" v-for="(item,index) in Visit" :key="index" v-if="index<3"
							@click="back_city(item)">
							{{item.name}}
						</view>
					</view>
				</view>

			</view>


			<!-- 城市列表 -->
			<view v-if="searchValue == ''" v-for="(item, index) in list" :id="getId(index)" :key="index">
				<view class="letter-header">{{ getId(index) }}</view>
				<view class="city-div" v-for="(city, i) in item" :key="i" @click="back_city(city)">
					<text class="city">{{city.name}} ({{city.mergename[2]}})</text>
				</view>
			</view>
			<!-- 搜索结果 -->
			<view class="city-div" v-for="(item, index) in searchList" :key="index" @click="back_city(item)">
				<text class="city">{{ item.name }} ({{item.mergename[2]}})</text>
			</view>
		</scroll-view>

		<!-- 右侧字母 -->
		<view class="letters" v-if="searchValue == ''">
			<view class="letters-item" @click="scrollTo('hot')">#</view>
			<view class="letters-item" v-for="item in letter" :key="item" @click="scrollTo(item)">{{ item }}</view>
		</view>

		<!-- 选中之后字母 -->
		<view class="mask" v-if="showMask">
			<view class="mask-r">{{selectLetter}}</view>
		</view>
	</div>
</template>

<script>
	import Citys from '../city.js';
	import app from '../../App.vue'
	export default {
		components: {},
		props: {},
		data() {
			return {
				statusBarHeight: this.statusBarHeight,
				ImgUrl: this.ImgUrl,
				letter: [],
				selectLetter: '',
				searchValue: '',
				scrollIntoId: '',
				list: [],
				tId: null,
				searchList: [],
				showMask: false,
				disdingwei: true,
				Visit: [], //最近访问
				position: '定位中...',
				longitude: '', //经度
				latitude: '', //纬度
				seconds: 3,
				po_tips: '重新定位',
				citys: [],
				selection: '',
				select: '',
				selectList: [{
					name: '全城'
				}],
				flag: false,
				jklList: []
			}
		},

		async created() {
			this.select = uni.getStorageSync('selection')
			this.selectList = uni.getStorageSync('selectList')
			uni.showLoading({
				title: "加载中..."
			})
			if (uni.getStorageSync('citys')) {
				this.citys = uni.getStorageSync('citys')
			} else {
				let res = await this.$request({
					url: 'common/city'
				})
				this.citys = res.data.data
				uni.setStorageSync('citys', res.data.data)
			}
			uni.hideLoading()
			//获取存储的最近访问
			var that = this
			uni.getStorage({
				key: 'Visit_key',
				success: function(res) {
					that.Visit = res.data
				}
			});
			//获取定位 经度纬度
			that.getWarpweft()
			//获取city.js 的程序字母
			var mu = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'W',
				'X',
				'Y',
				'Z'
			];
			var tmp = [];
			for (var i = 0; i < mu.length; i++) {
				var item = mu[i];
				for (var j = 0; j < this.citys.length; j++) {
					var py = this.citys[j].first;
					if (py == item) {
						if (tmp.indexOf(item) == -1) {
							this.list[i] = [this.citys[j]];
							tmp.push(item);
							this.letter.push(item.toUpperCase());
						} else {
							this.list[i].push(this.citys[j]);
						}
					}
				}
			}

		},
		methods: {
			onSelect() {
				let that = this,
					list = [];
				list.unshift({
					name: '全城'
				})
				this.citys.forEach((item, index) => {
					if (that.position.indexOf(item.name)!=-1) {
						this.citys.forEach((items, indexs) => {
							if (item.id == items.pid) {
								list.push(items)
							}
						})
					}
				})
				that.selectList = list;
				
				this.flag = !this.flag
			},
			onPosition() {
				let item = {
					name: this.position
				}
				if (this.position == '定位中...') {
					uni.showToast({
						title: "请稍等定位中...",
						icon: 'none',
						duration: 2000
					})
				} else {
					this.$emit('back_city', item);
					uni.setStorageSync('selection', this.position);
					uni.navigateBack({})
				}
			},
			getId(index) {
				return this.letter[index];
			},
			active() {
				let that = this,
					list = [];
				list.unshift({
					name: '全城'
				})
				this.citys.forEach((item, index) => {
					if (that.select.indexOf(item.name)!=-1) {
						this.citys.forEach((items, indexs) => {
							if (item.id == items.pid) {
								list.push(items)
							}
						})
					}
				})
				that.selectList = list;
				this.flag = !this.flag;
			},
			scrollTo(letter) {
				uni.vibrateShort();
				this.showMask = true
				this.selectLetter = letter == 'hot' ? '#' : letter
				setTimeout(() => {
					this.showMask = false
				}, 300);
				this.scrollIntoId = letter;
			},
			query(source, text) {
				let res = [];
				var self = this;
				res = source.filter(item => {
					const arr = [];
					let isHave = false;
					Object.keys(item).forEach(prop => {
						const itemStr = item[prop];
						self.isString(itemStr) &&
							itemStr.split(',').forEach(val => {
								arr.push(val);
							});
					});
					arr.some(val => {
						isHave = new RegExp('^' + text).test(val);
						return isHave;
					});
					return isHave;
				});
				return res;
			},
			isString(obj) {
				return typeof obj === 'string';
			},
			onInput(e) {
				const value = e.target.value;
				if (value !== '' && this.citys && this.citys.length > 0) {
					const queryData = this.query(this.citys, String(value).trim());
					this.searchList = queryData;
					this.disdingwei = false
				} else {
					this.searchList = [];
					this.disdingwei = true
				}
			},
			back_city(item) {
				// 标记
				let that = this
				if (item.name === '全城') {
					let selectionCity = uni.getStorageSync('selectionCity')
					this.$emit('getCitys', selectionCity)
					uni.setStorageSync('selection', selectionCity+'全城')
					this.$store.commit('selectedAddress', selectionCity);
					console.log(selectionCity)
					this.$store.commit('positionText', selectionCity);
					uni.navigateBack({
						delta: 1
					});
				} else {
					let pid = 0
					this.selectList = [{
						name: '全城'
					}]
					if (item.level == 3) {
						this.selection = `${item.mergename[2]+item.mergename[3]}`
						uni.setStorageSync('selection', `${item.mergename[2]+item.mergename[3]}`)
						uni.setStorageSync('selectionCity', item.mergename[2])
						this.citys.forEach((items, indexs) => {
							if (item.pid == items.pid) {
								this.selectList.push(items)
							}
						})
						uni.setStorageSync('selectList', this.selectList)
						uni.navigateBack({})
						if (item) {
							this.$emit('back_city', item);
							//unshift 把数据插入到首位，与push相反
							this.Visit.unshift(item)
							this.searchValue = "";
							this.disdingwei = true
							var arr = this.Visit
							//数组去重
							function distinct(arr) {
								let newArr = []
								for (let i = 0; i < arr.length; i++) {
									if (newArr.indexOf(arr[i]) < 0) {
										newArr.push(arr[i])
									}
								}
								return newArr
							}
							this.Visit = distinct(arr)
							uni.setStorage({
								key: 'Visit_key',
								data: this.Visit
							});
						} else {
							this.$emit('back_city', 'no');
						}
					} else {
						this.selectList = [{
							name: '全城'
						}]
						uni.setStorageSync('selection', item.name)
						this.selection = item.name
						this.citys.forEach((items, indexs) => {
							if (item.id == items.pid) {
								this.selectList.push(items)
							}
						})
						uni.setStorageSync('selectList', this.selectList)
						this.position = `${item.mergename[2]}`
						uni.navigateBack({})
						if (item) {
							this.$emit('back_city', item);
							this.Visit.unshift(item)
							this.searchValue = "";
							this.disdingwei = true
							var arr = this.Visit
							//数组去重
							function distinct(arr) {
								let newArr = []
								for (let i = 0; i < arr.length; i++) {
									if (newArr.indexOf(arr[i]) < 0) {
										newArr.push(arr[i])
									}
								}
								return newArr
							}
							this.Visit = distinct(arr)
							uni.setStorage({
								key: 'Visit_key',
								data: this.Visit
							});
						} else {
							this.$emit('back_city', 'no');
						}
					}
				}
			},
			getWarpweft() {
				var that = this
				that.po_tips = '定位中...'
				let countdown = setInterval(() => {
					that.seconds--;
					this.$request({
						url: 'common/getLocation',
						data: {
							lat: uni.getStorageSync('location').latitude,
							lng: uni.getStorageSync('location').longitude
						}
					}).then(res => {
						that.position = res.data.data.address_component.city
						if (that.seconds <= 0) {
							that.seconds = 3
							that.po_tips = '重新定位'
							clearInterval(countdown);
						}
					})
				}, 1000)
			}
		}
	};
</script>

<style scoped>
	.wrapper {
		position: fixed;
		z-index: 999999;
		background: #ffffff;
		height: 100%;
		width: 100%;
		top: 0px;
		left: 0px;
	}

	.dangqian {
		background-color: #FFFFFF;
		padding-left: 24upx;
		padding-right: 50upx;
		box-sizing: border-box;
		display: flex;
		justify-content: space-between;
		/* margin-top: 20rpx; */
		padding-top: 16upx;
		padding-bottom: 0upx;
	}

	.dq_list_box {
		padding-left: 24upx;
		padding-right: 50upx;
		margin-top: 0upx;
		display: flex;
		flex-wrap: wrap;
		overflow: hidden;
		transition: .5s;
		background-color: #ffffff;
		padding-bottom: 20upx;
	}

	.dq_list {
		width: 180upx;
		height: 70upx;
		border: 2upx solid #ccc;
		line-height: 70upx;
		border-radius: 8upx;
		margin-right: 40rpx;
		margin-top: 20rpx;
		overflow: hidden;

	}

	.left_title {
		color: #333;
	}

	.right_active_title {
		color: #A5A5A5;
	}

	.right_icon_box {
		width: 16upx;
		height: 26upx;
		background-image: url('');
		background-size: 100% 100%;
		margin-top: 4upx;
		margin-left: 10upx;
		transition: .5s;
	}

	.mask {
		position: absolute;
		bottom: 0upx;
		top: 83upx;
		left: 0upx;
		right: 0upx;
		width: 750upx;
		display: flex;
		justify-content: center;
		align-items: center;
		background: rgba(0, 0, 0, 0);
	}

	.mask-r {
		height: 120upx;
		width: 120upx;
		border-radius: 60upx;
		display: flex;
		background: rgba(0, 0, 0, 0.5);
		justify-content: center;
		align-items: center;
		font-size: 40upx;
		color: #FFFFFF
	}

	.content {
		height: 100%;
		width: 100%;
		background-color: #ffffff;
	}

	.header {
		height: 85upx;
		display: flex;
		justify-content: flex-start;
		align-items: center;
	}


	.back_div {
		width: 65upx;
		height: 100%;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.back_img {
		width: 35upx;
		height: 35upx;
	}

	.input {
		font-size: 28upx;
		width: 620upx;
		height: 55upx;
		border-radius: 40upx;
		background-color: #F5F5F5;
		padding-left: 20upx;
		padding-right: 20upx;
		box-sizing: border-box;
	}

	.title {
		font-size: 30upx;
		color: white;
	}

	.show {
		left: 0;
		width: 100%;
		transition: left 0.3s ease;
	}

	.hide {
		left: 100%;
		width: 100%;
		transition: left 0.3s ease;
	}


	.title {
		font-size: 30upx;
		color: white;
	}

	.calendar-list {
		position: absolute;
		top: 83upx;
		bottom: 0upx;
		width: 100%;
		height: 100%;
		background-color: #F4F4F4;
	}

	.letters {
		position: absolute;
		right: 30upx;
		bottom: 0px;
		width: 50upx;
		top: 260upx;
		color: #000;
		text-align: center;
		font-size: 24upx;
	}

	.letters-item {
		margin-bottom: 5upx;
	}

	.letter-header {
		height: 45upx;
		font-size: 22upx;
		color: #333333;
		padding-left: 24upx;
		box-sizing: border-box;
		display: flex;
		align-items: center;
		background-color: #F4F4F4;

	}

	.city-div {
		width: 100%;
		height: 85upx;
		background-color: #FFFFFF;
		border-bottom-width: 0.5upx;
		border-bottom-color: #ccc;
		border-bottom-style: solid;
		display: flex;
		align-items: center;
		margin-right: 35upx;
	}

	.city {
		font-size: 28upx;
		color: #000000;
		padding-left: 30upx;
	}

	.dingwei {
		width: 100%;
		padding-top: 25upx;
		box-sizing: border-box;
		margin-bottom: 26upx;
		padding-bottom: 10upx;
	}

	.dingwei_Tips {
		margin-left: 24upx;
		margin-bottom: 24upx;
		font-size: 24upx;
		color: #A5A5A5;
	}

	.dingwei_city {
		width: 100%;
		height: 60upx;
		padding-left: 55upx;
		padding-right: 70upx;
		box-sizing: border-box;
		display: flex;
		justify-content: space-between;
	}

	.dingwei_city_one {
		width: 185upx;
		height: 60upx;
		background-color: #FFFFFF;
		border-radius: 10upx;
		font-size: 32upx;
		color: #333333;
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 10upx 10upx 10upx 10upx;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.dingweis_div {
		display: flex;
		align-content: flex-end;
		align-items: center;
		font-size: 24upx;
		color: #000;
	}

	.dingweis {
		width: 32upx;
		height: 32upx;
		margin-right: 16rpx;
	}

	.dingwei_city_zuijin {
		display: flex;
		justify-content: flex-start;
	}

	.toright {
		margin-right: 25upx;
	}
</style>